function [mog] = gm_process_sensor( data, colour, verbose )
%GM_PROCESS_SENSOR Builds the sensor profile for the given sensor.
%   data:   output of 'reformat'
%   colour: 'r', 'g', 'b', ...
%
% Tip: the sensors of two houses can be automatically fit and compared
%      with the script 'run.m'

if (length(data)==0),
    mog = NaN;
    return;
end

% Constants
NCOMP = 2;  % Number of components

% Prepare the data
data = [getcolumn(data,1) getcolumn(data,2) getcolumn(data,2)];

% Get the GMM
[label, model, llh]    = emgm(data,NCOMP);
[labelC, modelC, llhC] = emgm(data,NCOMP);  % The control model

if (size(model.mu,2) ~= NCOMP | size(modelC.mu,2) ~= NCOMP ),
    [mog] = gm_process_sensor( data, colour, verbose );
    return;
end

for i=1:NCOMP,
    mog{i}.MU     = model.mu(:,i);
    mog{i}.SIGMA  = model.Sigma(:,:,i);
    mog{i}.WEIGHT = model.weight(i);
    
    mogC{i}.MU     = modelC.mu(:,i);
    mogC{i}.SIGMA  = modelC.Sigma(:,:,i);
    mogC{i}.WEIGHT = modelC.weight(i);
end

%d = gm_compare_jmef(mog,mogC)
%if (d > 5 | isnan(d))
%    fprintf('MOGs are too different: fitting again.\n');
%    [mog] = gm_process_sensor( data, colour, verbose );
    %return;
%end

if (verbose < 2)
    return;
end

% Plot
scatter(getcolumn(data,1),getcolumn(data,2),36,colour);
hold on;
for i=1:NCOMP,
    plot_gauss(mog{i}.MU, mog{i}.SIGMA);
end
hold off;

end
